/**
 * 音效管理类
 * 使用Web Audio API生成简单音效
 */
export class AudioManager {
    private audioContext: AudioContext | null = null;
    private enabled: boolean = true;

    constructor() {
        try {
            this.audioContext = new (window.AudioContext || (window as any).webkitAudioContext)();
        } catch (e) {
            console.warn('Web Audio API not supported');
            this.enabled = false;
        }
    }

    /**
     * 播放音效
     * @param frequency 频率（Hz）
     * @param duration 持续时间（毫秒）
     * @param type 波形类型
     */
    private playTone(
        frequency: number,
        duration: number = 100,
        type: OscillatorType = 'sine'
    ): void {
        if (!this.enabled || !this.audioContext) return;

        try {
            const oscillator = this.audioContext.createOscillator();
            const gainNode = this.audioContext.createGain();

            oscillator.connect(gainNode);
            gainNode.connect(this.audioContext.destination);

            oscillator.frequency.value = frequency;
            oscillator.type = type;

            // 音量包络
            gainNode.gain.setValueAtTime(0.3, this.audioContext.currentTime);
            gainNode.gain.exponentialRampToValueAtTime(0.01, this.audioContext.currentTime + duration / 1000);

            oscillator.start(this.audioContext.currentTime);
            oscillator.stop(this.audioContext.currentTime + duration / 1000);
        } catch (e) {
            // 忽略音频错误
        }
    }

    /**
     * 播放移动音效
     */
    playMove(): void {
        this.playTone(200, 50, 'sine');
    }

    /**
     * 播放旋转音效
     */
    playRotate(): void {
        this.playTone(300, 80, 'square');
    }

    /**
     * 播放消除音效
     */
    playClear(lines: number): void {
        const frequency = 400 + lines * 50;
        this.playTone(frequency, 150, 'sine');
    }

    /**
     * 播放硬下降音效
     */
    playHardDrop(): void {
        this.playTone(150, 100, 'square');
    }

    /**
     * 播放游戏结束音效
     */
    playGameOver(): void {
        if (!this.enabled || !this.audioContext) return;

        // 播放下降的音调
        const frequencies = [400, 300, 200, 100];
        frequencies.forEach((freq, index) => {
            setTimeout(() => {
                this.playTone(freq, 200, 'sine');
            }, index * 150);
        });
    }

    /**
     * 启用/禁用音效
     */
    setEnabled(enabled: boolean): void {
        this.enabled = enabled;
    }

    /**
     * 检查音效是否启用
     */
    isEnabled(): boolean {
        return this.enabled;
    }
}

